import threading
import time
import wx


class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="界面", size=(1200, 600))
        self.button4 = None
        self.button3 = None
        self.button2 = None
        self.button1 = None
        self.text2 = None
        self.text1 = None
        self.InitUI()

    def InitUI(self):
        panel = wx.Panel(self)

        font = wx.Font(14, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)

        vBoxAll = wx.BoxSizer(wx.VERTICAL)  # 整体盒子

        textBox = wx.BoxSizer(wx.HORIZONTAL)  # 文本框盒子
        self.text1 = wx.TextCtrl(panel, style=wx.TE_MULTILINE)
        self.text2 = wx.TextCtrl(panel, style=wx.TE_MULTILINE)
        self.text1.SetFont(font)
        self.text2.SetFont(font)
        textBox.Add(self.text1, proportion=1, flag=wx.EXPAND | wx.ALL, border=2)
        textBox.Add(self.text2, proportion=1, flag=wx.EXPAND | wx.ALL, border=2)

        vBoxAll.Add(textBox, proportion=1, flag=wx.EXPAND | wx.ALL, border=2)

        buttonBox = wx.GridSizer(2, 2, 2, 2)  # 创建2x2的网格布局盒子
        # GridSizer对象有四个参数：rows、columns、vgap和hgap。其中，rows和columns分别指定网格的行数和列数，
        # vgap和hgap分别指定相邻控件之间的纵向和横向间距。
        # 添加4个按钮到网格布局
        self.button1 = wx.Button(panel, label="Button1")
        self.button2 = wx.Button(panel, label="Button2")
        self.button3 = wx.Button(panel, label="Button3")
        self.button4 = wx.Button(panel, label="Button4")
        self.button1.SetFont(font)
        self.button2.SetFont(font)
        self.button3.SetFont(font)
        self.button4.SetFont(font)

        self.button1.Bind(wx.EVT_BUTTON, self.thread1)
        self.button2.Bind(wx.EVT_BUTTON, self.test2)
        self.button3.Bind(wx.EVT_BUTTON, self.test3)
        self.button4.Bind(wx.EVT_BUTTON, self.test4)

        buttonBox.Add(self.button1, flag=wx.EXPAND)
        buttonBox.Add(self.button2, flag=wx.EXPAND)
        buttonBox.Add(self.button3, flag=wx.EXPAND)
        buttonBox.Add(self.button4, flag=wx.EXPAND)

        vBoxAll.Add(buttonBox, proportion=0, flag=wx.EXPAND | wx.ALL, border=2)

        panel.SetSizer(vBoxAll)

        self.Show()

    def thread1(self, event):
        # 让 test 函数在子线程中运行
        thread = threading.Thread(target=self.test, args=())
        # 下面是设置守护线程：如果在程序中将子线程设置为守护线程，则该子线程会在主线程结束时自动退出
        thread.daemon = True
        thread.start()  # 启动线程

    def test(self):
        inf = "hello"
        self.text1.SetValue(inf)
        wx.Yield()
        time.sleep(5)
        self.text1.SetValue("inf")

    def test2(self):
        inf = "world"
        self.text2.SetValue(inf)

    def test3(self):
        inf = ""
        self.text1.SetValue(inf)

    def test4(self):
        inf = ""
        self.text2.SetValue(inf)


if __name__ == "__main__":
    app = wx.App()
    frame = MyFrame()
    app.MainLoop()
